package com.example.tys.daggermvp.network.retrofit2;

import com.example.tys.daggermvp.network.okhttpclient.BaseOkHttpClient;
import com.example.tys.daggermvp.network.retrofit2.converter.fastJson.FastJsonConverterFactory;

import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * @author tys
 * @date 2018/4/22
 */
public abstract class BaseRetrofit {

    public Retrofit get() {
        return new Retrofit.Builder()
                .baseUrl(getApiEndpoint().getEndpoint())
                .client(getOkHttpClient())
                .addCallAdapterFactory(getCallAdapterFactory())
                .addConverterFactory(getConverterFactor())
                //build 添加默认的属性
                //1.添加默认CallAdapterFactory,顺序依次为:add添加的CallAdapter->默认CallAdapter(DefaultCallAdapterFactory)
                //默认处理retrofit2.Call的情况
                //2.添加默认ConverterFactory,顺序依次为:默认的ConverterFactory(BuiltInConverters)->add添加的ConverterFactory
                //默认处理okhttp3.RequestBody 和okhttp3.ResponseBody
                .build();

    }

    protected OkHttpClient getOkHttpClient() {
        return new BaseOkHttpClient().get();
    }

    /**
     * BaseRetrofit,默认添加RxJavaCallAdapterFactory.大多数情况，应该都不需要用到RxJavaCallAdapter.
     * okHttp3自帶的enqueue和execute就足够了。默认Android平台Retrofit的CallBack在main 线程执行.
     *
     * {@code https://github.com/square/retrofit/tree/master/retrofit-adapters/rxjava2}
     * Available types: RxJava2CallAdapterFactory.java ===> get
     * Observable<T>, Observable<Response<T>>, and Observable<Result<T>> where T is the body type.
     * Flowable<T>, Flowable<Response<T>> and Flowable<Result<T>> where T is the body type.
     * Single<T>, Single<Response<T>>, and Single<Result<T>> where T is the body type.
     * Maybe<T>, Maybe<Response<T>>, and Maybe<Result<T>> where T is the body type.
     *
     * @return 要添加的CallAdapter
     */
    protected CallAdapter.Factory getCallAdapterFactory() {
        return retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory.createAsync();
    }

    protected Converter.Factory getConverterFactor() {
        return retrofit2.converter.gson.GsonConverterFactory.create();
    }

    /**
     * 构建baseUrl
     *
     * @return
     */
    protected abstract ApiEndpoint getApiEndpoint();

    interface ApiEndpoint {
        /**
         * 返回baseUrl，以“/”结尾
         *
         * @return
         */
        String getEndpoint();
    }
}
